# -*- coding:utf-8 -*-
import sys
reload(sys) 
sys.setdefaultencoding( "utf-8" ) 
import json
from decimal import Decimal
import pymysql
import time
def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError
#连接数据库
#dbstr=sys.argv[1]
#dbstr = 'brokers_dl'
city=sys.argv[2]
dbstr = 'brokers_'+str(city)
tbl = 'broker'
print dbstr
#conn=pymysql.connect(host='rds1tu038044m8zub4o7.mysql.rds.aliyuncs.com',user='zhuge',passwd='zhuge1116',db=dbstr,port=3306,charset="utf8")
#conn=pymysql.connect(host='182.92.96.120',user='zhugef_offline',passwd='2d573c729a&^%460adc4c5547ff7e7%8',db=dbstr,port=3306,charset="utf8")
conn=pymysql.connect(host='rds1tu038044m8zub4o7.mysql.rds.aliyuncs.com',user='data_rw',passwd='2q6RmfhGm9uGXeSrlJUQImRcPzWU33mE',db=dbstr,port=3306,charset="utf8",cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()
cur.execute('select count(*) from %s'% tbl)
#获取数据库中记录总条数
count_all=cur.fetchone()['count(*)']
print count_all
#每一次获取1000条数据
page_count=1000;
#cur = conn.cursor(cursorclass=pymysql.cursors.DictCursor)
#打开文件，准备写
filename = "%s/%s" % (city, tbl)
file = open(filename, "w")
#for($i=0;$i<=($sell_gov_count/$page_count);$i++)
j=0
phonelist=[]
page_num =  count_all/page_count + 1
 
for i in range(0, page_num):
    time.sleep(0.1)
    print 'i=',i
    try:
        query = 'select phone from %s limit %d,%d'%(tbl,i*page_count,page_count)
        print 'query=', query
        cur.execute(query)
    except Exception as e:
        time.sleep(5)
        print 'exception=', e
        conn=pymysql.connect(host='rds1tu038044m8zub4o7.mysql.rds.aliyuncs.com',user='data_rw',passwd='2q6RmfhGm9uGXeSrlJUQImRcPzWU33mE',db=dbstr,port=3306,charset="utf8")
        #cur = conn.cursor(cursorclass=pymysql.cursors.DictCursor)
        print 'query=', query
        cur.execute(query)
    results=cur.fetchall()
    for row in results:
        j = j+1
        if (row['phone'] !=  ""):
            phonelist.append(row['phone'])
file.write(json.dumps(phonelist,default=default))
file.close()
